package com.demo.youxuanmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.entity.Product;
import com.demo.youxuanmall.mapper.ProductMapper;
import com.demo.youxuanmall.service.ProductService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    private final ProductMapper productMapper;

    @Override
    public Page<Product> getProductPage(Page<Product> page, String keyword) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        // 只查询上架状态的商品
        wrapper.eq(Product::getStatus, 1);
        
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like(Product::getName, keyword)
                            .or()
                            .like(Product::getSubtitle, keyword));
        }
        
        wrapper.orderByDesc(Product::getCreateTime);
        return baseMapper.selectPage(page, wrapper);
    }

    /**
     * 管理后台分页查询商品列表（带关键字搜索）
     */
    public Page<Product> getAdminProductPage(Page<Product> page, String keyword) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like(Product::getName, keyword)
                            .or()
                            .like(Product::getSubtitle, keyword));
        }
        
        wrapper.orderByDesc(Product::getCreateTime);
        return baseMapper.selectPage(page, wrapper);
    }

    @Override
    public List<Map<String, Object>> getHotProducts(int limit) {
        try {
            return productMapper.getHotProducts(limit);
        } catch (Exception e) {
            log.error("获取热门商品失败", e);
            return Collections.emptyList();
        }
    }
    
    @Override
    public List<Product> getProductsByCategory(Long categoryId) {
        if (categoryId == null) {
            return Collections.emptyList();
        }
        
        try {
            return list(new LambdaQueryWrapper<Product>()
                    .eq(Product::getCategoryId, categoryId)
                    .eq(Product::getStatus, 1)
                    .eq(Product::getIsDeleted, 0)
                    .orderByDesc(Product::getCreateTime));
        } catch (Exception e) {
            log.error("获取分类商品失败: categoryId={}", categoryId, e);
            return Collections.emptyList();
        }
    }
    
    @Override
    public List<Product> searchProducts(String keyword) {
        if (keyword == null || !StringUtils.hasText(keyword)) {
            return Collections.emptyList();
        }
        
        try {
            return list(new LambdaQueryWrapper<Product>()
                    .like(Product::getName, keyword)
                    .or()
                    .like(Product::getSubtitle, keyword)
                    .eq(Product::getStatus, 1)
                    .eq(Product::getIsDeleted, 0)
                    .orderByDesc(Product::getCreateTime));
        } catch (Exception e) {
            log.error("搜索商品失败: keyword={}", keyword, e);
            return Collections.emptyList();
        }
    }
    
    @Override
    public Product getProductById(Long id) {
        if (id == null) {
            return null;
        }
        
        try {
            return getById(id);
        } catch (Exception e) {
            log.error("获取商品详情失败: id={}", id, e);
            return null;
        }
    }
    
    @Override
    public List<Product> getRelatedProducts(Long categoryId, Long productId, int limit) {
        if (categoryId == null || productId == null) {
            return new ArrayList<>();
        }
        
        try {
            LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Product::getCategoryId, categoryId)
                   .ne(Product::getId, productId)
                   .eq(Product::getStatus, 1)
                   .eq(Product::getIsDeleted, 0)
                   .orderByDesc(Product::getSales)
                   .last("LIMIT " + limit);
            
            return list(wrapper);
        } catch (Exception e) {
            log.error("获取相关商品失败: categoryId={}, productId={}", categoryId, productId, e);
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<Product> listEnabledProducts() {
        try {
            LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Product::getStatus, 1)
                   .eq(Product::getIsDeleted, 0)
                   .orderByDesc(Product::getCreateTime);
            
            return list(wrapper);
        } catch (Exception e) {
            log.error("获取所有上架商品失败", e);
            return new ArrayList<>();
        }
    }
    
    @Override
    public Result<Boolean> deleteProduct(Long productId) {
        if (productId == null) {
            return Result.error("商品ID不能为空");
        }
        
        try {
            // 查询商品是否存在
            Product product = getById(productId);
            if (product == null) {
                return Result.error("商品不存在");
            }
            
            // 逻辑删除，将is_deleted设为1
            product.setIsDeleted(1);
            boolean updated = updateById(product);
            
            if (updated) {
                return Result.success(true);
            } else {
                return Result.error("删除商品失败");
            }
        } catch (Exception e) {
            log.error("删除商品失败: id={}", productId, e);
            return Result.error("系统错误，删除商品失败");
        }
    }
    
    @Override
    public Result<Boolean> updateProductStatus(Long productId, Integer status) {
        if (productId == null || status == null) {
            return Result.error("参数不能为空");
        }
        
        try {
            // 查询商品是否存在
            Product product = getById(productId);
            if (product == null) {
                return Result.error("商品不存在");
            }
            
            // 更新商品状态（上架/下架）
            product.setStatus(status);
            boolean updated = updateById(product);
            
            if (updated) {
                return Result.success(true);
            } else {
                return Result.error("更新商品状态失败");
            }
        } catch (Exception e) {
            log.error("更新商品状态失败: id={}, status={}", productId, status, e);
            return Result.error("系统错误，更新商品状态失败");
        }
    }
    
    @Override
    public Result<Product> saveOrUpdateProduct(Product product) {
        if (product == null) {
            return Result.error("商品信息不能为空");
        }
        
        try {
            // 设置默认值
            if (product.getStatus() == null) {
                product.setStatus(0); // 默认下架状态
            }
            
            if (product.getStock() == null) {
                product.setStock(0); // 默认库存为0
            }
            
            if (product.getSales() == null) {
                product.setSales(0); // 默认销量为0
            }
            
            product.setIsDeleted(0); // 默认未删除
            
            // 保存或更新
            boolean success = saveOrUpdate(product);
            
            if (success) {
                return Result.success(product);
            } else {
                return Result.error("保存商品失败");
            }
        } catch (Exception e) {
            log.error("保存或更新商品失败", e);
            return Result.error("系统错误，保存商品失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Page<Product>> searchProductsForAdmin(String keyword, Long categoryId, Integer status, int pageNum, int pageSize) {
        try {
            // 创建分页对象
            Page<Product> page = new Page<>(pageNum, pageSize);
            
            // 构建查询条件
            LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
            
            // 按关键词搜索（商品名称或副标题）
            if (StringUtils.hasText(keyword)) {
                wrapper.and(w -> w.like(Product::getName, keyword)
                        .or()
                        .like(Product::getSubtitle, keyword));
            }
            
            // 按分类ID筛选
            if (categoryId != null) {
                wrapper.eq(Product::getCategoryId, categoryId);
            }
            
            // 按状态筛选
            if (status != null) {
                wrapper.eq(Product::getStatus, status);
            }
            
            // 只查询未删除的商品
            wrapper.eq(Product::getIsDeleted, 0);
            
            // 按创建时间倒序排序
            wrapper.orderByDesc(Product::getCreateTime);
            
            // 执行查询
            Page<Product> productPage = page(page, wrapper);
            
            return Result.success(productPage);
        } catch (Exception e) {
            log.error("管理员搜索商品失败: keyword={}, categoryId={}, status={}", keyword, categoryId, status, e);
            return Result.error("搜索商品失败: " + e.getMessage());
        }
    }
    
    @Override
    public Result<Page<Product>> getAllProducts(int pageNum, int pageSize) {
        try {
            // 创建分页对象
            Page<Product> page = new Page<>(pageNum, pageSize);
            
            // 构建查询条件 - 只查询未删除的商品
            LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Product::getIsDeleted, 0)
                   .orderByDesc(Product::getCreateTime);
            
            // 执行查询
            return Result.success(page(page, wrapper));
        } catch (Exception e) {
            log.error("获取所有商品失败", e);
            return Result.error("获取商品列表失败");
        }
    }
} 